<html>
<div id="button" class="toolstrip-button">
  Show Image
</div>

<script>
  var imgArr = [];
  button.onclick = handleClick;
  /**
   * @TODO: Find out how to call the handleClick-Method in another tab if it is
   * possible at all. Then the doubleclick-handler should open the biggest image
   * in every tab following the current
   */
//  button.ondblclick = handleDoubleClick;

  chrome.self.onConnect.addListener(function(port) {
    port.onMessage.addListener(function(images) {
		console.log("Got biggest image...");
		imgArr = [];
		for(var img in images)	{
			imgArr.push(images[img]);
		}
    });
  });

  function handleClick() {
	for(var img in imgArr)	{
		if (imgArr[img] != "") {
			console.log("Processing image...");
			chrome.tabs.getSelected(null,function (tab)	{
				chrome.tabs.update(tab.id,{url:imgArr[img]});
			})
		}	else	{
			console.error("Error retireving image...");
		}
	}
  }
  
  function handleDoubleClick()	{
  		var selected_tab = null;
		var process = false;
		chrome.tabs.getSelected(null,function(tab)	{
			selected_tab = tab.id;
		})
		chrome.windows.getCurrent(function(window)	{
			chrome.tabs.getAllInWindow(window.id,function(tabs)	{
				for(var key in tabs)	{
					var tab = tabs[key];
					if (process) {
						chrome.tabs.get(tab.id,function(nTab)	{
//							handleClick();
							nTab.handleClick();
							for(var test in nTab)	{
								console.log(test+": "+nTab[test]);
							}
						})
					}
					if(tab.id==selected_tab)	process=true;
				}
			})
		})
  }
</script>
</html>
